<template>
    <div>
      <h1>WebSocket 测试</h1>
      <div>
        <input v-model="message" placeholder="输入消息..." />
        <button @click="sendMessage">发送</button>
      </div>
      <div>
        <h3>连接状态: {{ connectionStatus }}</h3>
      </div>
      <div>
        <h3>收到的消息:</h3>
        <ul>
          <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
        </ul>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        message: '',
        messages: [],
        connectionStatus: '未连接',
        socket: null
      };
    },
    mounted() {
      this.connect();
    },
    methods: {
      connect() {
        // 创建WebSocket连接（请确保替换为你的后端实际地址）
        this.socket = new WebSocket('ws://localhost:10011/my-websocket');
        
        this.socket.onopen = () => {
          console.log('WebSocket连接已建立');
          this.connectionStatus = '已连接';
        };
        
        this.socket.onmessage = (event) => {
          console.log('收到消息:', event.data);
          this.messages.push(event.data);
        };
        
        this.socket.onclose = (event) => {
          console.log('WebSocket连接已关闭:', event.reason);
          this.connectionStatus = '已断开';
          
          // 可选：尝试重新连接
          setTimeout(() => {
            this.connect();
          }, 5000);
        };
        
        this.socket.onerror = (error) => {
          console.error('WebSocket错误:', error);
          this.socket.close();
        };
      },
      sendMessage() {
        if (this.socket && this.message) {
          this.socket.send(this.message);
          this.message = '';
        }
      }
    },
    beforeUnmount() {
      if (this.socket) {
        this.socket.close();
      }
    }
  };
  </script>
  
  <style scoped>
  ul {
    list-style-type: none;
    padding-left: 0;
  }
  
  li {
    padding: 5px 0;
  }
  </style>